/**
 * 
 */
package per.lxy.wechat.net.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import per.lxy.wechat.net.WinNetworkApi;
import per.lxy.wechat.util.MyStringUtils;
/**
 * windows network api
 * 
 * */
public class WinNetworkApiImpl implements WinNetworkApi {
	
	private static final int TASKLIST_PROCESS_INDEX = 1;
	
	private static final int NETSTAT_PROCESS_INDEX = 4;

	private static final int NETSTAT_HOSTINFO_INDEX = 2;

	private static final String CM_TASKLIST = "cmd.exe /c tasklist";
	private static final String CM_NETSTAT = "cmd.exe /c netstat -ano";

	@Override
	public Set<String> findPidByName(List<String> processNameList) throws IOException {
		Runtime rt = Runtime.getRuntime();
		Process p = rt.exec(CM_TASKLIST);
		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
		
		String line = null;
		
		Set<String> processIds = new HashSet<>();
		while ((line = bufferedReader.readLine()) != null) {
			for(String name:processNameList) {
				if(line.indexOf(name) != -1) {
					processIds.add(MyStringUtils.extracTextInfo(line,TASKLIST_PROCESS_INDEX));
				}
			}
		}
		return processIds;
	}

	@Override
	public Set<String> findTarServerIpByName(List<String> processNameList) throws IOException {
		
		Set<String> processIds = findPidByName(processNameList);
		
		Runtime rt = Runtime.getRuntime();
		Process p = rt.exec(CM_NETSTAT);
		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
		
		String line = null;
		Set<String> hostinfoSet = new HashSet<>();
		while ((line = bufferedReader.readLine()) != null) {
			String processId = MyStringUtils.extracTextInfo(line,NETSTAT_PROCESS_INDEX);
			if(processIds.contains(processId)) {
				hostinfoSet.add(MyStringUtils.extracTextInfo(line,NETSTAT_HOSTINFO_INDEX));
			}
		}
		return MyStringUtils.formatHostinfo(hostinfoSet);
	}
	


}